//index.js
//获取应用实例
const app = getApp()

const Dialog = require('../../zanui/dialog/dialog');
const DialogUser = require('../../zanui/dialog_user/dialog');
import { file_uploadone, postcard_get, postcard_update, user_follow, user_start } from "../../utils/request/request_json"

Page({
    data: {
        list: { "title": "个人姓名", topImageUrl: "../image/hart.png", bottomImageUrl: "../image/color.png", userIconUrl: "../image/showimg.png", background_img: "", push_list: [{ key: "电话", value: "18523412415" }, { key: "就职", value: "北京上海广州" }, { key: "地址", value: "XXXXXXXXXXXXXXXXXXXXX" }, { key: "邮箱", value: "XXXXXXXXXXXXXXXXXXXXX" }] },
        l_name: "",
        l_value: "",
        changeVal: "",
        state: "",
        topImageUrl: "",
        bottomImageUrl: "",
        userIconUrl: "",
        addOrEditState: 1, // 1（编辑） 2（保存） 3 (关注) 4(待审核) 5（禁止）
        addAnimate: "",
        cssAnimate: "left",
        feed_style: {
            x: "80%",
            y: "80%"
        },
        screen: {
            width: "",
            height: "",
        },
        preX: 0,
        preY: 0,
        background_img: "",
        allList: "",
        scene: "",
        clickAni:1,
        text_form:"",
    },
    onShareAppMessage: function(res) {
        if (res.from === 'menu') {
            // 来自页面内转发按钮
        }
        console.log('/pages/index/index?scene=' + app.globalData.opid)
        return {
            title: '分享我的名片',
            path: '/pages/index/index?scene=' + app.globalData.opid
        }
    },
    onLoad: function(options) {
        console.log("load",options)
        var self = this;
        app.getUserAuth(DialogUser)
        var scene = "";
        if (JSON.stringify(options) != "{}") {
            scene = decodeURIComponent(options.scene);
        }else{
            // scene = 
        }
        self.setData({
            scene: scene
        })
        wx.setStorageSync('scene', scene)
        if (!app.globalData.opid) {
            app.login(function() {
                self.postcard_get(scene);
            })
        } else {
            self.postcard_get(scene);
        }
        
    },
    onShow:function() {
        if(app.globalData.pageIdx != 0){
            app.globalData.pageIdx = 0;
            var scene = wx.getStorageSync('scene')
            this.postcard_get(scene);
        }
    },
    postcard_get(scene, success, fail) {
        var self = this;
        var data = {
            "openid": app.globalData.opid,
            "pull_openid": scene,
        }
        postcard_get(data, function(res) {
            console.log(res);
            if (res.data.state == true) {
                // addOrEditState: 1, // 1（编辑） 2（保存） 3 (关注) 4(待审核) 5（禁止）
                // self.data.allList = res.data.data;
                self.data.list = res.data.data
                self.data.list.push_list = JSON.parse(res.data.data.push_list);
                self.setData({
                    list: self.data.list
                })
                if(res.data.data.is_start){
                    self.setData({
                        cssAnimate: "right"
                    })
                }else{
                    self.setData({
                        cssAnimate: "left"
                    })
                }

                wx.setStorageSync("card_list", self.data.list)
                self.changeState(res.data.data.flag);
                
            }
        }, function(res) {

        })
    },
    changeState(state){
        var self = this;
        if (state == 2) {
            self.setData({
                addOrEditState: 4
            })
        } else if (state == 3) {
            self.setData({
                addOrEditState: 5
            })
        } else if (state == 1) {
            self.setData({
                addOrEditState: 1
            })
        } else if (state == 0) {
            self.setData({
                addOrEditState: 3
            })
        } else if (state == -1 || state == 3) {
            self.setData({
                addOrEditState: 5
            })
        }
    },
    postcard_update(form_text) {
        var self = this;
        var form_id = form_text;
        if(!form_text){
            form_id = "";
        }
        var data = {
            "openid": app.globalData.opid,
            "push_list": JSON.stringify(self.data.list.push_list),
            "form_id":form_id
        }
        postcard_update(data, function(res) {
            if (res.data.state == true) {
                self.postcard_get("")
            }
        }, function(res) {  })
    },
    changeAllState() {
        if (this.data.addOrEditState == 1) {
            this.setData({
                addOrEditState: 2
            })
        } else if (this.data.addOrEditState == 2) {
            wx.showModal({
                title:"提示",
                content:"您确认要保存修改么？",
                success:(res)=>{
                    console.log(res);
                    this.setData({
                        addOrEditState: 1
                    })
                    if(res.cancel){
                        return;
                    }
                    this.postcard_update(this.text_form);
                }
            })
            
        }
    },
    saveSubmit(e){
        this.text_form = e.detail.formId.toString();
        this.setData({
            text_form:this.text_form
        })
    },
    judgeState() {
        //1编辑
        //2保存
        //3.查看状态
        //4.待审核
        //5.禁止
        if (this.data.addOrEditState == 1) {
            return false
        } else if (this.data.addOrEditState == 2) {
            return true
        } else {
            return false
        }
    },
    //事件处理函数
    bindViewTap: function() {
        wx.navigateTo({
            url: '../logs/logs'
        })
    },
    bindname(e) {
        this.data.l_name = e.detail.value
    },
    bindvalue(e) {
        this.data.l_value = e.detail.value
    },
    bindchangeVal(e) {
        this.data.changeVal = e.detail.value
    },
    editList(e) {
        var self = this;
        if (!this.judgeState()) {
            return;
        }
        self.setData({
            state: "edit"
        })
        var idx = e.currentTarget.dataset.index;
        
        if (idx == "title") {
            this.setData({
                changeVal: self.data.list.push_list.title,
            })

        } else {
            this.setData({
                changeVal: self.data.list.push_list.data[idx].value,
            })
        }
        Dialog({
            title: '添加列表',
            content: '',
            slot: true,
            selector: '#zan-dialog-edit',
            showCancelButton: true,
        }).then((res) => {
            if (res.type == "cancel") {
                self.setData({
                    changeVal: "",
                    state: ""
                })
                return;
            }
            if (idx == "title") {
                self.data.list.push_list.title = self.data.changeVal;
                self.updateList(self.data.list);
            } else {
                self.data.list.push_list.data[idx].value = self.data.changeVal;
                self.updateList(self.data.list);
            }
        }).catch((res) => {
            self.setData({
                changeVal: "",
                state: ""
            })
            return;
        })
    },
    addList(val) {
        var self = this;
        self.setData({
            state: "add"
        })
        Dialog({
            title: '添加列表',
            content: '',
            slot: true,
            name: "zan-dialog-add",
            selector: '#zan-dialog-test',
            showCancelButton: true,
        }).then((res) => {
            if (res.type == "cancel") {
                self.setData({
                    l_name: "",
                    l_value: "",
                    state: ""
                })
                return;
            }
            var list = { key: self.data.l_name, value: self.data.l_value }
            if (!list.key) {
                wx.showToast({
                    title: "字段名不可为空",
                    icon: "none",
                    mask: true,
                })
                return;
            }
            self.data.list.push_list.data.push(list);
            self.updateList(self.data.list);
        }).catch((res) => {
            self.setData({
                l_name: "",
                l_value: "",
                state: ""
            })
            return;
        })
    },
    updateList(val) {
        //用于更新列表数据，将输入数据初始化
        var self = this;
        self.setData({
            list: val,
            l_name: "",
            l_value: "",
            state: "",
        })
        self.changeState(self.data.list)
    },
    choseImage(e) {
        var self = this;
        var that = this;
        if (!this.judgeState()) {
            return;
        }
        var imageState = e.currentTarget.dataset.image;
        wx.chooseImage({
            count: 1,
            success: (res) => {
                switch (imageState) {
                    case "top":
                        file_uploadone(res.tempFilePaths[0], "key", (res) => {
                            var data = JSON.parse(res.data);
                            if (data.state == true) {
                                self.data.list.push_list.topImageUrl = data.data[0].file_name
                                that.setData({
                                    list: self.data.list,
                                    addOrEditState:2
                                })
                            }
                        }, () => {})
                        break;
                    case "bottom":
                        file_uploadone(res.tempFilePaths[0], "key", (res) => {
                            var data = JSON.parse(res.data);
                            if (data.state == true) {
                                // console.log("bottom0:", self.data.list.push_list)
                                self.data.list.push_list.bottomImageUrl = data.data[0].file_name
                                //self.data.list = self.data.list
                                that.setData({
                                    list: self.data.list,
                                    addOrEditState:2
                                })
                            }
                        }, () => {})
                        break;
                    case "usericon":
                        file_uploadone(res.tempFilePaths[0], "key", (res) => {
                            var data = JSON.parse(res.data);
                            if (data.state == true) {
                                self.data.list.push_list.userIconUrl = data.data[0].file_name
                                that.setData({
                                    list: self.data.list,
                                    addOrEditState:2
                                })
                            }
                        }, () => {})
                        break;
                    case "bgimg":
                        file_uploadone(res.tempFilePaths[0], "key", (res) => {
                            var data = JSON.parse(res.data);
                            if (data.state == true) {
                                self.data.list.push_list.background_img = data.data[0].file_name
                                that.setData({
                                    list: self.data.list,
                                    addOrEditState:2
                                })
                            }
                        }, () => {})
                        break;
                }
            },
            fail: (res) => {
            }
        })
    },
    delList(e) {
        var self = this;
        var idx = e.currentTarget.dataset.index;
        self.data.list.push_list.data.splice(idx, 1);
        console.log(self.data.list.push_list);
        self.updateList(self.data.list);
    },
    listChangeData(val) {
    },
    addAnimateFun() {
        var self = this;
        // if(this.data.clickAni == 1){
            // self.setData({
            //     clickAni:0,
            // })
            var _base = "http://hospital-1252338888.file.myqcloud.com/music/";
            var _url = ["1.mp3","2.mp3"];
            var i = Math.round(Math.random())
            wx.getSystemInfo({
                success:(res)=>{
                    if (res.platform == "android") {
                        const innerAudioContext = wx.createInnerAudioContext()
                        innerAudioContext.autoplay = true
                        innerAudioContext.src = _base+_url[i];
                        innerAudioContext.onPlay((res) => {
                        })
                    }else{
                        wx.playBackgroundAudio({
                            dataUrl:_base+_url[i],
                            success:function(res){console.log(res)},
                            fail:function(res){console.log(res)}
                        })
                    }
                }
            })
            this.setData({
                addAnimate: "heartAnimation"
            })
            setTimeout(() => {
                self.setData({
                    addAnimate: "",
                    cssAnimate: "right",
                })
            }, 500)
        // }
       
    },
    user_follow() {
        var self = this;
        var data = {
            openid: app.globalData.opid,
            pull_openid: this.data.list.pull_openid,
            flag: 1
        }
        user_follow(data, function(res) {
            if(res.data.state){
                self.data.list.is_follow = 1;
                self.setData({
                    list:self.data.list
                })
            }
        }, function(res) {})
    },
    formSubmit(e) {
        
        var data = {
            openid: app.globalData.opid,
            pull_openid: this.data.list.pull_openid,
            form_id: e.detail.formId.toString()
        }
        user_start(data, function(res) {
        }, function(res) {
        })
    },
    downImage(e){
        if(this.data.addOrEditState != 1 && this.data.addOrEditState != 4){
            return;
        }
        var url = e.currentTarget.dataset.url;

        wx.showModal({
            title:"提示",
            content:"保存图片？",
            success:(res)=>{
                if(res.cancel){
                    return;
                }
                wx.downloadFile({
                    url:url,
                    success:(res)=>{
                        // console.log(res);
                        wx.saveImageToPhotosAlbum({  
                            filePath: res.tempFilePath,  
                            success: function (res) {  
                            //   console.log(res)  
                            },  
                            fail: function (res) {  
                            //   console.log(res)  
                            //   console.log('fail')  
                            }  
                        })  
                    },
                    fail:(res)=>{
                        // console.log(res);
                    }
                })
            }
        })

        
    }
})